package com.tubang.logistics.controller.orderV2;


import com.tubang.common.constant.Constants;
import com.tubang.common.util.GsonQuick;
import com.tubang.common.util.IdGenerator;
import com.tubang.common.util.MsgCode;
import com.tubang.common.util.ResultData;
import com.tubang.component.entity.AddressEntity;
import com.tubang.component.service.IAddressService;
import com.tubang.component.util.RequestUtil;
import com.tubang.logistics.entity.GoodsEntity;
import com.tubang.logistics.entity.LogisticsOrderEntity;
import com.tubang.logistics.entity.LogisticsOrderGoodsEntity;
import com.tubang.logistics.entity.TransportEntity;
import com.tubang.logistics.service.IGoodsService;
import com.tubang.logistics.service.ILogisticsOrderGoodsService;
import com.tubang.logistics.service.ILogisticsOrderService;
import com.tubang.logistics.service.ITransportService;
import com.tubang.logistics.vo.ChangeStatusVo;
import com.tubang.logistics.vo.OrderSupplyVo2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单货源 前端控制器
 * </p>
 *
 * @author maxl
 * @since 2017-12-31
 */
@RestController
@RequestMapping("/supply")
public class OrderSupplyController {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Resource
    private IGoodsService goodsService;


    @Resource
    private IAddressService addressService;


    @Resource
    private ITransportService transportService;


    @Resource
    private ILogisticsOrderService logisticsOrderServices;

    @Resource
    private ILogisticsOrderGoodsService logisticsOrderGoodsService;

    /**
     * 新增或更新货源列表
     *
     * @param request
     * @return
     */
    @PostMapping(value = "insertOrUpdateSupplyOrder")
    public ResultData insertOrUpdateSupplyOrder(HttpServletRequest request) {
        //获取数据
        String receivePostJson = RequestUtil.receivePostJson(request);
        OrderSupplyVo2 orderSupplyVo2 = GsonQuick.toObjectDate(receivePostJson, OrderSupplyVo2.class);
        logger.info("method发布货源:[insertOrUpdateSupplyOrder]supplyOrderVo=========={}", GsonQuick.getGson().toJson(orderSupplyVo2));
        try {
            if (orderSupplyVo2 == null) {
                return ResultData.result(false);
            }
            long now = System.currentTimeMillis();

            //保存订单
            LogisticsOrderEntity order = orderSupplyVo2.getOrder();
            order.setUpdateTime(new Date(now));
            //order.setStatusCode(String.valueOf(Constants.ORDER_STATUS_CODE_PENDING));
            //order.setStatusCodeDesc("待接单");
            order.setNum(IdGenerator.INSTANCE.nextId());
            order.setInvoiceFlag(Constants.DEFAULT_VAULE_ZERO);
            order.setCreateUserId(order.getUserId());
            order.setCreateUserType(order.getUserType());
            order.setOrderStatusCode(Constants.ORDER_STATUS_SUPPLY);
            order.setOrderStatusCodeDesc("货源发布");

            logisticsOrderServices.insertOrUpdate(order);
            //保存运输详情
            TransportEntity transport = orderSupplyVo2.getTransport();
            transport.setUpdateTime(new Date(now));
            transport.setOrderId(order.getId());
            transportService.insertOrUpdate(transport);

            //保存货物
            GoodsEntity goodsBasic = orderSupplyVo2.getGoodsBasic();
            goodsBasic.setParentId(Constants.DEFAULT_VAULE_ZERO);
            goodsBasic.setUpdateTime(new Date(now));
            goodsBasic.setShipperOrderId(order.getId());
            goodsBasic.setTransportId(transport.getId());
            goodsBasic.setGoodsStatus(Constants.ORDER_WAITING_PICK_UP_GOODS);
            goodsService.insertOrUpdate(goodsBasic);
            LogisticsOrderGoodsEntity tkoBase = new LogisticsOrderGoodsEntity();
            tkoBase.setLogisticsOrderId(order.getId());
            tkoBase.setGoodsId(goodsBasic.getId());
            tkoBase.setCreateTime(new Date(now));
            tkoBase.setUpdateTime(new Date(now));
            tkoBase.setStatusCode(Constants.DEFAULT_VAULE_ONE);
            tkoBase.setStatusCodeDesc("未调度");
            tkoBase.setEnable(true);
            logisticsOrderGoodsService.insertOrUpdate(tkoBase);
            List<GoodsEntity> goods = orderSupplyVo2.getGoods();
            //goods总吨数
            BigDecimal goodWeight = new BigDecimal(0);
            for (GoodsEntity good : goods) {
                good.setUpdateTime(new Date(now));
                good.setParentId(goodsBasic.getId());
                good.setShipperOrderId(order.getId());
                good.setTransportId(transport.getId());
                good.setGoodsStatus(Constants.ORDER_WAITING_PICK_UP_GOODS);
                goodWeight = goodWeight.add(good.getWeight());
                goodsService.insertOrUpdate(good);
                LogisticsOrderGoodsEntity tko = new LogisticsOrderGoodsEntity();
                tko.setLogisticsOrderId(order.getId());
                tko.setGoodsId(good.getId());
                tko.setCreateTime(new Date(now));
                tko.setUpdateTime(new Date(now));
                tko.setStatusCode(Constants.DEFAULT_VAULE_ONE);
                tko.setStatusCodeDesc("未调度");
                tko.setEnable(true);
                logisticsOrderGoodsService.insertOrUpdate(tko);
            }
            goodsBasic.setWeight(goodWeight);
            goodsBasic.setLeftWeight(goodWeight);
            order.setGoodsName(goodsBasic.getName());
            order.setCarriageDeal(order.getCarriage());

            Double carriage = order.getCarriage();
            if (carriage != null) {
                order.setAmount(goodWeight.multiply(new BigDecimal(order.getCarriage().doubleValue())).doubleValue());
                order.setAmountDeal(goodWeight.multiply(new BigDecimal(order.getCarriage().doubleValue())).doubleValue());
            }
            order.setGoodsWeight(goodWeight.doubleValue());
            goodsService.insertOrUpdate(goodsBasic);
            //保存收货地址
            //发货人
            StringBuffer addrFrom = new StringBuffer();
            AddressEntity addressFrom = orderSupplyVo2.getAddressFrom();
            addressService.insertOrUpdate(addressFrom);
            transport.setFromUserAddressId(addressFrom.getId());
            transport.setFromUserId(addressFrom.getUserId());
            order.setAddrFrom(addrFrom.append(addressFrom.getProvinceName()).append(addressFrom.getCityName()).append(addressFrom.getDistrictName()).toString());
            //收货人
            StringBuffer addrTo = new StringBuffer();
            AddressEntity addresTo = orderSupplyVo2.getAddresTo();
            addressService.insertOrUpdate(addresTo);
            transport.setToUserAddressId(addresTo.getId());
            transport.setToUserId(addresTo.getUserId());
            order.setAddrTo(addrTo.append(addresTo.getProvinceName()).append(addresTo.getCityName()).append(addresTo.getDistrictName()).toString());
            transportService.insertOrUpdate(transport);
            logisticsOrderServices.insertOrUpdate(order);
            logger.info("[OrderShipperController]<== method[insertOrUpdateSupplyOrder],新增或者修改的数据为 ：[{}] ", receivePostJson);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[insertOrUpdateSupplyOrder], 新增或者修改失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 查询货源详情
     *
     * @param orderId
     * @return
     */
    @GetMapping(value = "selectSupplyOrderById")
    public ResultData selectSupplyOrderById(@RequestParam String orderId) {
        logger.info("method查询货源详情:[selectSupplyOrderById]orderId=========={}", orderId);
        try {
            LogisticsOrderEntity order = logisticsOrderServices.selectById(orderId);
            if (order == null) {
                return ResultData.result(true);
            }
            OrderSupplyVo2 orderSupplyVo2 = new OrderSupplyVo2();
            orderSupplyVo2.setOrder(order);
            TransportEntity transportEntity = transportService.selectByOrderId(orderId);
            orderSupplyVo2.setTransport(transportEntity);

            if (transportEntity != null) {
                AddressEntity from = addressService.selectById(transportEntity.getFromUserAddressId());
                AddressEntity to = addressService.selectById(transportEntity.getToUserAddressId());
                orderSupplyVo2.setAddressFrom(from);
                orderSupplyVo2.setAddresTo(to);
            }
            GoodsEntity baseGoods = goodsService.selectBaseGoodsByLogisticsOrderId(order.getId());
            orderSupplyVo2.setGoodsBasic(baseGoods);
            List<GoodsEntity> goodsEntities = goodsService.selectGoodssByLogisticsOrderId(order.getId(), null);
            orderSupplyVo2.setGoods(goodsEntities);

            logger.info("[OrderShipperController]<== method[selectSupplyOrderById],订单详情数据为 ：[{}] ", orderSupplyVo2);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[selectSupplyOrderById], 异常 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 更新订单状态
     *
     * @param
     * @return
     */
    @PostMapping(value = "updateSupplyOrderStatus")
    public ResultData updateSupplyOrderStatus(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            ChangeStatusVo changeStatusVo = GsonQuick.toObject(receivePostJson, ChangeStatusVo.class);
            //更新状态
            logisticsOrderServices.updateSupplyOrderStatus(changeStatusVo);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[updateSupplyOrderStatus], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 删除订单
     *
     * @param
     * @return
     */
    @GetMapping(value = "deleteSupplyOrder")
    public ResultData deleteSupplyOrder(@RequestParam String orderId) {
        try {
            //获取数据
            LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(orderId);
            if (logisticsOrderEntity == null)
                ResultData.result(false).setCode(MsgCode.ORDER_DATA_ERROR).setMsg(MsgCode.ORDER_DATA_ERROR_DESC);
            logisticsOrderEntity.setEnable(false);
            logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[deleteSupplyOrder], 删除失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

}
